package com.zhang.first.day02;

import com.zhang.first.utils.ClickEvent;
import com.zhang.first.utils.ClickEventSource;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @title: 基本转换算子 filter  , flatMap
 * @author: zhang
 * @date: 2022/1/15 22:00
 */
public class Example3 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new ClickEventSource())
                .filter(new FilterFunction<ClickEvent>() {
                    @Override
                    public boolean filter(ClickEvent value) throws Exception {
                        return "Mary".equals(value.name);
                    }
                })
                .print();

        env
                .addSource(new ClickEventSource())
                .filter(r -> r.name.equals("Mary"))
                .print();


        env
                .addSource(new ClickEventSource())
                .filter(new MyFilter())
                .print();

        //可以使用flatMap实现filter
        env
                .addSource(new ClickEventSource())
                .flatMap(new FlatMapFunction<ClickEvent, ClickEvent>() {
                    @Override
                    public void flatMap(ClickEvent value, Collector<ClickEvent> out) throws Exception {
                        if ("Mary".equals(value.name)) out.collect(value);
                    }
                })
                .print();


        env.execute();
    }

    private static class MyFilter implements FilterFunction<ClickEvent> {
        @Override
        public boolean filter(ClickEvent value) throws Exception {
            return "Mary".equals(value.name);
        }
    }
}
